package com.matt.controller;

import com.alipay.api.AlipayApiException;
import com.dotflat.fin.cnst.Const;
import com.dotflat.fin.domain.FinPlanOrder;
import com.dotflat.fin.service.AliPayService;
import com.dotflat.fin.service.FinPlanOrderService;
import com.matt.commons.exception.BusinessException;
import com.matt.domain.Clientele;
import com.matt.foundation.model.ErrorCode;
import com.matt.foundation.model.StatusResponse;
import com.matt.remoteCall.SsoCallService;
import com.matt.service.ClienteleService;
import com.matt.service.ContractService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

import static org.springframework.web.bind.annotation.RequestMethod.GET;

/**
 * Filename: AliAppPay.java <br>
 * <p>
 * Description: 支付宝app支付<br>
 *
 * @author:Ron<br>
 * @version: 1.0 <br>
 * @Createtime: 2020-11-07 <br>
 * <p>
 * Modification History:
 * Date         Author          Version            Description
 * ---------------------------------------------------------*
 * 2019-12-07      Ron           v1.0              第一次创建
 * @Copyright: Copyright (c)2019 byRon<br>
 */
@Slf4j
@RestController
@RequestMapping("/other_system/pay/alipay")
@Api(tags = "其他系统 - 支付宝支付")
public class OtherSystemPayAliController  {

    @Autowired
    private AliPayService payService;

    @Autowired
    private SsoCallService ssoCallService;

    @Autowired
    FinPlanOrderService finPlanOrderService;

    @Autowired
    ContractService contractService;

    @Autowired
    ClienteleService clienteleService;

    @RequestMapping(value = "/prepare",method = RequestMethod.POST)
    public Object getAlipayOrder(@RequestParam String sourceId,
                                 @RequestParam String openId,
                                 @RequestParam String clienteleId,
                                 @RequestParam(defaultValue = "0") int useDeposit,
                                 @RequestParam Integer resourceType,
                                 @RequestParam String resourceId){

        Const.RES_TYPE resType = Const.RES_TYPE.get(resourceType);

        Clientele clientele = null;
        Map result = null;

        if (resType == Const.RES_TYPE.PRODUCT){
            FinPlanOrder order = finPlanOrderService.get(null, null, resourceId);

            if (order == null){
                throw new BusinessException(ErrorCode.MATERIAL_NOT_EXIST, "账单不存在");
            }

            clientele = clienteleService.getById(order.getClienteleId());

            // 请求预付单id
            result = payService.prepare(clientele, null, resourceType, order, useDeposit);
        }else if(resType == Const.RES_TYPE.PHOTOPRINT && com.dotflat.fin.utils.excelUtil.StringUtils.isNotBlank(clienteleId)){
            result = payService.prepare(clientele, openId, resType.codeOf(), resourceId, useDeposit);
        }

        if (result == null){
            return StatusResponse.error(ErrorCode.SIGN_ERROR, "支付失败");
        }

        return StatusResponse.success(result);
    }

    /**
     * 回调验证
     * @param request
     * @return
     */
//   tuo51.com/api/mobile/pay/ali/pay_notifier
    @RequestMapping(value = "/notify",method = RequestMethod.POST)
    public boolean alipayNotify(HttpServletRequest request) {
        //获取支付宝POST过来反馈信息
        log.debug("支付宝回调");

        Map<String, String> params = new HashMap<>();
        Map requestParams = request.getParameterMap();

        for (Object o : requestParams.keySet()) {
            String name = (String) o;
            String[] values = (String[]) requestParams.get(name);
            String valueStr = String.join(",", values);
            params.put(name, valueStr);
        }

        log.debug("params: " + params);

        try {
             return payService.processAliPayOrderResult(params);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        return false;
    }


    @RequestMapping(value = "/check", method = GET )
    public Object wxOrderCheck(@RequestParam("resourceType") Integer resourceType,
                               @RequestParam("outTradeNo") String outTradeNo) {

        payService.check(resourceType, outTradeNo);

        return StatusResponse.success();
    }
}
